import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { ApesFormatEmitEvent } from '@shared/apes/core';
import { deepClone } from '../../../../utils/utils';

@Component({
  selector: 'cad-tree-menu',
  template: `
    <apes-input-group [apesSuffix]="suffixIconSearch" class="cad-menu-search">
      <input type="search" apes-input placeholder="主组名称搜索" (keyup)="searchName($event)" [(ngModel)]="mainMenuName"/>
    </apes-input-group>
    <ng-template #suffixIconSearch>
      <i apes-icon apesType="close-circle" class="cad-tree-menu-clear" apesTheme="fill" *ngIf="mainMenuName" (click)="clearSearchName()"
    ></i>
      <img *ngIf="mainMenuName == null" [src]="'./assets/tmp/img/fn/search.png'"/>
    </ng-template>
    <ng-container *ngIf="treeNodes.length != 0">
      <div class="cad-tree-menu" *ngFor="let node of treeNodes" (click)="onSelect(node)">
        <div>{{node.code}}-{{node.name}}</div>
      </div>
    </ng-container>
    <ng-container *ngIf="treeNodes.length == 0">
      <apes-empty style="text-align: center"></apes-empty>
      <!--<div>暂无数据</div>-->
    </ng-container>

  `,
  styleUrls:[`cad-tree-menu.component.scss`],
})
export class CadTreeMenuComponent implements OnInit, OnChanges {
  @Input() isLoading: boolean = false;
  @Input() nodes;
  @Output() selected = new EventEmitter();

  originalData: any[] = [];
  treeNodes: any[] = [];
  mainMenuName :any;

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.nodes) {
      let nodes = this.resolveData(changes.nodes.currentValue);
      this.originalData = Object.keys(nodes).length == 0 ? [] : nodes;
      this.mainMenuName = null;
      this.treeNodes = deepClone(this.originalData);
      // console.log('主菜单',this.nodes);
    }
  }

  resolveData(param) {
    for (let i = 0, len = param.length; i < len; i++) {
      let tempJson = param[i];
      tempJson.key = tempJson.id;
      tempJson.title = tempJson.name;
      if (tempJson.children && tempJson.children.length > 0) {
        tempJson.selectable = false;
        this.resolveData(tempJson.children);
      } else {
        tempJson.isLeaf = true; // 后端无法判断是否为叶子节点
      }
    }
    return param;
  }

  onSelect(node) {
    // 选择为叶子节点的时候触发
    if (node.isLeaf && !this.isLoading) {
      this.selected.emit(node);
    }
  }

  searchName(param) {
    let value = param.target.value.toUpperCase();
    if (value) {
      this.treeNodes = this.filtrationData(this.originalData,value);
    }else {
      this.treeNodes = deepClone(this.originalData);
    }
  }

  filtrationData(original,keyword){
    const arr = [];
    for (let item of original) {
      if (item['code'].match(keyword) !== null || item['name'].match(keyword) !== null) {
        arr.push(item);
      }
    }
    return arr;
  }

  clearSearchName(){
    this.mainMenuName = null;
    this.treeNodes = deepClone(this.originalData);
  };

}
